package net.vinote.smart.platform.service.action;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;

import net.vinote.smart.platform.comm.PlatformConst;
import net.vinote.smart.platform.module.database.BeanEntityFactory;
import net.vinote.smart.platform.module.database.DBManager;
import net.vinote.smart.platform.module.database.DBManagerFactory;
import net.vinote.smart.platform.module.database.DBTransaction;
import net.vinote.smart.platform.module.database.Table;
import net.vinote.smart.platform.module.database.bo.BizObject;
import net.vinote.smart.platform.module.database.bo.DBQuery;
import net.vinote.smart.platform.module.log.RunLogger;
import net.vinote.smart.platform.service.SRE;
import net.vinote.smart.platform.service.bean.AppInfo;
import net.vinote.smart.platform.service.bean.CodeLibrary;
import net.vinote.smart.platform.service.util.AutoInjection;
import net.vinote.smart.platform.service.util.Permission;
import net.vinote.smart.platform.service.util.Permission.PermissionEnum;

public class AppInfoAction {
	@AutoInjection
	private String appID;

	@AutoInjection
	private String userID;

	@AutoInjection
	private String newAppID;

	/**
	 * 删除子系统信息
	 * 
	 * @return
	 * @throws SQLException
	 */
	@Permission(PermissionEnum.SMART_APP_INFO_DELETE)
	public String deleteAppInfo(DBTransaction tx) throws SQLException {
		int result = PlatformConst.SQL_UNDO;
		// -----第一步:删除子系统各栏目开放的角色--------
		DBManager bm = DBManagerFactory.getInstance("role_object_rela");
		tx.join(bm);
		bm.deleteWhereSql(
				"objectType=? and exists(select 1 from APP_ITEM AI where AI.APPID=? and AI.APPID=ObjectID )",
				"AppItem", appID);
		// -----第二步:删除子系统开放的角色--------
		tx.join(bm);
		bm.deleteWhereSql("objectType=? and objectID=?", "AppInfo", appID);
		// -----第三步: 删除子系统栏目----------
		bm = DBManagerFactory.getInstance("app_item");
		tx.join(bm);
		bm.deleteWhereSql("appID=?", new String[] { appID });
		// -----第四步: 删除子系统-------
		bm = DBManagerFactory.getInstance("app_info");
		tx.join(bm);
		result = bm.deleteWhereSql("appID=?", new String[] { appID });
		return result == 1 ? PlatformConst.SUCCESS : PlatformConst.FAIL;
	}

	/**
	 * @return
	 * @throws SQLException
	 */
	@Permission(PermissionEnum.SMART_APP_INFO_QUERY)
	public String isExists() throws SQLException {
		DBManager bm = DBManagerFactory.getInstance("app_info");
		return bm.createQuery(new String[] { "1" }, "appID=?")
				.setParamVal(appID).getResultList().size() > 0 ? PlatformConst.SUCCESS
				: PlatformConst.FAIL;
	}

	@Permission({ PermissionEnum.SMART_APP_INFO_UPDATE,
			PermissionEnum.SMART_APP_ITEM_UPDATE })
	public String rename(DBTransaction tx) throws SQLException {
		int result = PlatformConst.SQL_UNDO;
		// -----第一步:更新APP_INFO--------
		DBManager bm = DBManagerFactory.getInstance("app_info");
		tx.join(bm);
		bm.update(new String[] { "appID" }, "appID=?", newAppID, appID);
		// -----第二步:更新APP_ITEM--------
		bm = DBManagerFactory.getInstance("app_item");
		tx.join(bm);
		bm.update(new String[] { "appID" }, "appID=?", newAppID, appID);
		// -----第三步: 更新权限表----------
		bm = DBManagerFactory.getInstance("app_info");
		tx.join(bm);
		bm.deleteWhereSql("appID=?", new String[] { appID });
		// -----第四步: 删除子系统-------
		tx.join(bm);
		result = bm.deleteWhereSql("appID=?", new String[] { appID });
		return result == 1 ? PlatformConst.SUCCESS : PlatformConst.FAIL;
	}

	public List<AppInfo> getAllAppInfo() {
		List<AppInfo> appList = new ArrayList<AppInfo>();
		DBManager bm = DBManagerFactory.getInstance("APP_INFO");
		try {
			List<BizObject> boList = bm.createQuery(
					SRE.getAttribute(
							PlatformConst.SRE_PREFIX_TABLE + "APP_INFO",
							Table.class).getFieldsName(),
					"isinuse='1' order by sortno").getResultList();
			for (BizObject bo : boList) {
				AppInfo app = new AppInfo();
				app.setAppID(bo.getAttribute("appID"));
				app.setAppName(bo.getAttribute("appName"));
				app.setIsInuse(bo.getAttribute("isInuse"));
				app.setLogo(bo.getAttribute("logo"));
				app.setMinLogo(bo.getAttribute("minLogo"));
				app.setSortNo(bo.getAttribute("sortNo"));
				app.setUrl(bo.getAttribute("url"));
				app.setWorkBench(bo.getAttribute("workbench"));
				appList.add(app);
			}
		} catch (SQLException e) {
			RunLogger.getLogger().log(Level.SEVERE, e.getMessage(), e);
		}
		return appList;
	}

	public List<CodeLibrary> getAppInfoSubjectList() throws SQLException {
		DBManager bm = DBManagerFactory.getInstance("code_library");
		List<BizObject> list = bm
				.createQuery(
						new String[] { "ItemNO", "ItemName" },
						"codeNo=? and EXISTS("
								+ "select 1 from app_info ai where ai.subject=o.ITEMNO and EXISTS("
								+ "select 1 from role_object_rela ror where ror.objectType=? and ror.objectid=ai.APPID and exists ("
								+ "select 1 from user_role_rela urr where urr.roleid=ror.roleID and urr.userid=?)"
								+ ") and ai.isinuse='1' ) order by sortno")
				.setParamVal("AppInfoSubject", "AppInfo", userID)
				.getResultList();
		List<CodeLibrary> clList = new ArrayList<CodeLibrary>(list.size());
		for (BizObject bo : list) {
			CodeLibrary cl = new CodeLibrary();
			BeanEntityFactory.getInstance().getObject(cl, bo);
			clList.add(cl);
		}
		return clList;
	}

	public List<AppInfo> getAppsByUserIdAndSubject(String userID, String subject) {
		DBManager bm = DBManagerFactory.getInstance("app_info");
		DBQuery query;
		List<AppInfo> appList = new ArrayList<AppInfo>();
		try {
			query = bm
					.createQuery(
							SRE.getTable("app_info").getFieldsName(),
							"subject=? and EXISTS(select 1 from role_object_rela ror where ror.objectType='AppInfo' and ror.objectid=O.APPID and exists (select 1 from user_role_rela urr where urr.roleid=ror.roleID and urr.userid=?)) and isinuse='1' order by sortno")
					.setParamVal(subject, userID);
			List<BizObject> list = query.getResultList();
			for (BizObject bo : list) {
				AppInfo app = new AppInfo();
				BeanEntityFactory.getInstance().getObject(app, bo);
				appList.add(app);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return appList;
	}

	/**
	 * @param userID
	 *            the userID to set
	 */
	public void setUserID(String userID) {
		this.userID = userID;
	}

}
